<title>系统角色 - 数据表格</title>
<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-header">数据操作</div>
                <div class="layui-card-body">
                    <script type="text/html" id="role_operate_btn">
                        <div class="layui-btn-container">
                            <button class="layui-btn" lay-event="add">添加</button>
                            <button class="layui-btn layui-btn-danger" lay-event="batchDel">批量删除</button>
                        </div>
                    </script>
                    <table class="layui-hide" id="role_table" lay-filter="role-table-filter"></table>

                    <script type="text/html" id="role-table-operate">
                        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
                        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
                    </script>
                </div>
            </div>
        </div>
    </div>
</div>

<style type="text/css">
    .ztree li span.button.switch.level0 {
        visibility: hidden;
        width: 1px;
    }

    .ztree li ul.level0 {
        padding: 0;
        background: none;
    }

    .ztree * {
        padding: 0;
        margin: 0;
        font-size: 12px;
        font-family: Verdana, Arial, Helvetica, AppleGothic, sans-serif
    }

    .ztree li {
        padding: 0;
        margin: 0;
        list-style: none;
        line-height: 17px;
        text-align: left;
        white-space: nowrap;
        outline: 0
    }

    .ztree li span.button {
        height: 17px;
    }

    .ztree li a.curSelectedNode {
        padding-top: 0px;
        background-color: transparent;
        color: black;
        height: 21px;
        opacity: 0.8;
    }
</style>
<script>
    layui.use(['admin', 'table'], function () {
        var table = layui.table
            , admin = layui.admin
            , form = layui.form
            , view = layui.view
            , tableId = "role_table"
            , powerRoot = {id: "0"};
        var setting = {
            async: {
                enable: true,
                autoParam: ["id"]
            },
            data: {
                simpleData: {
                    enable: true,
                    idKey: "id",
                    pIdKey: "parent",
                    rootPId: 0
                }
            },
            check: {
                enable: true//checkbox
            },
            view: {
                showIcon: showIcon,
                nameIsHTML: true, //允许name支持html
                selectedMulti: false
                // , fontCss: {'color': 'blue', 'font-family': '微软雅黑'}
                , dblClickExpand: dblClickExpand
            },
            edit: {
                enable: false,
                editNameSelectAll: false
            },
            callback: {
                onClick: onClick//点击事件
            }
        };

        function onClick(event, treeId, treeNode, clickFlag) {
            if (treeNode.level > 0) {
                //实现单击展开
                var treeObj = getTreeObj();
                treeObj.expandNode(treeNode);
            }
        }

        //取消双击展开功能
        function dblClickExpand(treeId, treeNode) {
            return false;
        }

        //设置图标
        function showIcon(treeId, treeNode) {
            return true;
        }

        //获取树对象
        function getTreeObj() {
            return $.fn.zTree.getZTreeObj("powerZtree");
        }

        table.render({
            elem: '#' + tableId
            , url: '/sys/role/list'
            // ,width: admin.screen() > 1 ? 892 : ''
            // ,height: 332
            //开启头部工具栏
            , toolbar: '#role_operate_btn'
            , cols: [[
                {type: 'checkbox', fixed: 'left'}
                , {field: 'id', title: 'ID', sort: true, fixed: 'left'}
                , {field: 'roleName', title: '角色名称'}
                , {
                    field: 'powers', title: '关联权限', templet: function (d) {
                        var powers = "";
                        var powerList = d.powerList;
                        if (powerList) {
                            for (var item in powerList) {
                                powers += powerList[item].powerName + ",";
                            }
                            powers = remove_last_char(powers);
                        }
                        return powers;
                    }
                }
                , {field: 'gmtTime', title: '创建时间'}
                , {width: 178, align: 'center', fixed: 'right', title: '操作', toolbar: '#role-table-operate'}
            ]]
            , page: true
            , limit: 10
            , limits: [10, 15, 20, 25, 30]
            , text: '对不起，加载出现异常！'
        });

        //监听工具条
        table.on('tool(role-table-filter)', function (obj) {
            var data = obj.data;
            if (obj.event === 'del') {
                layer.confirm('真的删除行么', function (index) {
                    admin.req({
                        url: '/sys/role/del'
                        , type: 'post'
                        , data: {ids: data.id}
                        , done: function (res) {
                            layer.msg(res.msg)
                            obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                            layer.close(index);
                        }
                    });
                });
            } else if (obj.event === 'edit') {
                common('编辑角色信息', 'role-content-edit', '/sys/role/update', 'post', data);
            }
        });

        table.on('toolbar(role-table-filter)', function (obj) {
            switch (obj.event) {
                case 'batchDel':
                    var checkStatus = table.checkStatus(tableId)
                        , checkData = checkStatus.data; //得到选中的数据
                    var length = checkData.length;
                    if (length === 0) {
                        return layer.msg('请选择数据');
                    }
                    var ids = ''
                    for (item in checkData) ids += checkData[item]["id"] + ",";
                    layer.confirm('确定删除这 ' + length + ' 条数据吗？', function () {
                        admin.req({
                            url: '/sys/role/del'
                            , type: 'post'
                            , data: {ids: ids}
                            , done: function (res) {
                                layer.msg(res.msg)
                                table.reload(tableId);
                            }
                        });
                    });
                    break;
                case 'add':
                    common('添加角色信息', 'role-content-add', '/sys/role/save', 'post');
                    break;
            }
        });

        function common(title, id, url, ajaxType, data) {
            var resData;
            admin.popup({
                title: title
                , area: ['450px', '550px']
                , id: id
                , success: function (layero, index) {
                    view(this.id).render('sys/role/model').done(function () {
                        //初始化弹框
                        form.render(null, 'role-model-filter');
                        admin.req({
                            url: "/sys/power/get/powers"
                            , type: 'get'
                            , async: false
                            , success: function (res) {
                                res.data[0].open = true
                                res.data[0].iconClose = "/zTree_v3/img/1_open.png"
                                res.data[0].iconOpen = "/zTree_v3/img/1_open.png"
                                $.fn.zTree.init($("#powerZtree"), setting, res.data);
                                resData = res.data;
                            }
                        });
                        var treeObj = $.fn.zTree.getZTreeObj("powerZtree");
                        if (data) {
                            if (data.powerList.length > 0) {
                                data.powerList.push(powerRoot);//添加根节点
                            }
                            for (var item in data.powerList) {
                                var node = treeObj.getNodeByParam("id", data.powerList[item].id);
                                var parent = node.getParentNode();
                                if (null != parent && !parent.open) {
                                    treeObj.expandNode(parent, true, true);
                                }
                                treeObj.checkNode(node, true, false);
                            }
                            //渲染弹框
                            form.val('role-model-filter', data)
                        }
                        //监听提交
                        form.on('submit(role-submit-filter)', function (data) {
                            var nodes = treeObj.getCheckedNodes(true),
                                powerIds = "";
                            for (var i = 0; i < nodes.length; i++) {
                                if (nodes[i].id !== "0") {
                                    powerIds += nodes[i].id + ","
                                }
                            }
                            if (powerIds !== "") {
                                data.field.powerIds = remove_last_char(powerIds)
                            }
                            admin.req({
                                url: url
                                , type: ajaxType
                                , data: data.field
                                , done: function (res) {
                                    layer.msg(res.msg);
                                    table.reload(tableId); //重载表格
                                    layer.close(index); //执行关闭
                                }
                            });
                        });
                    });
                }
            });
        }
    });
</script>